package ru.pb.game.handlers;

import java.util.HashMap;
import java.util.Map;

import ru.pb.game.handlers.interfaces.IAdminCommandHandler;
import ru.pb.game.objects.model.players.Player;
import ru.pb.game.objects.model.players.enums.RANK;
import ru.pb.global.xml.holder.AbstractHolder;

public class AdminCommandHandler extends AbstractHolder
{
	private static AdminCommandHandler _instance;

	private Map<String, IAdminCommandHandler> _datatable = new HashMap<String, IAdminCommandHandler>();

	public static AdminCommandHandler getInstance()
	{
		if(_instance == null)
			_instance = new AdminCommandHandler();
		return _instance;
	}

	private AdminCommandHandler()
	{
		//
	}

	public void registerAdminCommandHandler(IAdminCommandHandler handler)
	{
		for(Enum<?> e : handler.getAdminCommandEnum())
		{
			_datatable.put(e.toString().toLowerCase(), handler);
		}
	}

	public IAdminCommandHandler getAdminCommandHandler(String adminCommand)
	{
		String command = adminCommand;
		if(adminCommand.indexOf(" ") != -1)
		{
			command = adminCommand.substring(0, adminCommand.indexOf(" "));
		}
		return _datatable.get(command.toLowerCase());
	}

	public void useAdminCommandHandler(Player activeChar, String adminCommand)
	{
		if(activeChar.getPlayerInfos().getRank() != RANK.RANK_GAMEMASTER.ordinal())
		{
			return;
		}

		String[] wordList = adminCommand.split(" ");
		IAdminCommandHandler handler = _datatable.get(wordList[0].toLowerCase());
		if(handler != null)
		{
			try
			{
				for(Enum<?> e : handler.getAdminCommandEnum())
				{
					if(e.toString().equalsIgnoreCase(wordList[0]))
					{
						handler.useAdminCommand(e, wordList, adminCommand, activeChar);
						break;
					}
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public int size()
	{
		return _datatable.size();
	}

	@Override
	public void clear()
	{
		_datatable.clear();
	}
}